import json
import glob
from datetime import datetime
from plane_hebavior_check.behavior_plane import check_close_adsb, check_altitude_states, check_open_adsb, check_vertical_movement, check_speed_change, check_supersonic_flight, check_takeoff_landing, check_ground_hold, check_working_mode, check_circling_mode, visualize_working_modes, check_region_entry, check_region_approach_departure, process_plane_behavior, save_plane_behavior_results
# from ship_sample import check_close_ais, check_speed_high


# 读取飞机模拟数据
def read_planedata():
    data_input = []
    track_data = {}
    file_path_list = [
        './data/1748623163.json',
        './data/1748623212.json',
        './data/1748623281.json',
        './data/1748623337.json'
    ]
    # file_path_list = glob.glob('data/data_converted_20250318/*.json')
    max_timestamp = 0
    for file_path in file_path_list:
        with open(file_path, 'r', encoding='utf-8') as file:
            data_json = json.load(file)
            timestamp = float(data_json['time'])
            if timestamp > max_timestamp:
                max_timestamp = timestamp
            for item in data_json['states']:
                track_id = item[0]
                if track_data.get(track_id, None) is None:
                    track_data[track_id] = {
                        'trackId': track_id,
                        'trackData': []
                    }
                
                speed_str = item[9]
                speed = 0.0
                try:
                    if speed_str:
                        speed = float(speed_str)
                except (ValueError, TypeError):
                    speed = 0.0

                altitude_str = item[13]
                track_data[track_id]['trackData'].append({
                    'timestamp': timestamp,
                    'longitude': round(float(item[5]), 6),
                    'latitude': round(float(item[6]), 6),
                    'altitude': float(altitude_str) if altitude_str is not None and altitude_str.isnumeric() else 0,
                    'speed': speed,
                    'on_ground': altitude_str == 'ground'
                })
    for track_item in track_data.values():
        data_input.append(track_item)
    return data_input, max_timestamp

if __name__ == '__main__':
    # 读取文件生成飞机实时状态类输入数据
    data_input, now_timestamp = read_planedata()
    print(f'data_input: {data_input}')
    # 运行算法程序-关闭adsb信号
    data_output1 = check_close_adsb(data_input, now_timestamp)
    # 打印算法结果
    print(f'check_close_adsb: {data_output1}')
    # 运行算法程序-高度分层
    data_output2 = check_altitude_states(data_input, now_timestamp)
    # 打印算法结果
    print(f'check_altitude_states: {data_output2}')
    # 运行算法程序-打开adsb信号
    data_output3 = check_open_adsb(data_input, now_timestamp)
    # 打印算法结果
    print(f'check_open_adsb: {data_output3}')
    # 运行算法程序-爬升下降
    data_output4 = check_vertical_movement(data_input, now_timestamp)
    # 打印算法结果
    print(f'check_vertical_movement: {data_output4}')
    # 运行算法程序-加速减速
    data_output5 = check_speed_change(data_input, now_timestamp)
    # 打印算法结果
    print(f'check_speed_change: {data_output5}')
    # 运行算法程序-超音速飞行
    data_output6 = check_supersonic_flight(data_input, now_timestamp)
    # 打印算法结果
    print(f'check_supersonic_flight: {data_output6}')
    # 运行算法程序-起飞降落
    data_output7 = check_takeoff_landing(data_input, now_timestamp)
    # 打印算法结果
    print(f'check_takeoff_landing: {data_output7}')
    # 运行算法程序-地面驻停
    data_output8 = check_ground_hold(data_input, now_timestamp)
    # 打印算法结果
    print(f'check_ground_hold: {data_output8}')
    
    # 将起飞、降落和地面驻停的航段定义为排除区域
    exclusion_segments = data_output7 + data_output8
    
    # 运行算法程序-盘旋模式识别（优先于工作模式）
    data_output9 = check_circling_mode(data_input, now_timestamp, exclusion_segments=exclusion_segments)
    # 打印算法结果
    print(f'check_circling_mode: {data_output9}')
    
    # 将盘旋模式也加入排除区域，确保工作模式与盘旋模式互斥
    exclusion_segments = exclusion_segments + data_output9
    # 运行算法程序-工作模式识别
    data_output10 = check_working_mode(data_input, now_timestamp, exclusion_segments=exclusion_segments)
    # 打印算法结果
    print(f'check_working_mode: {data_output10}')

    # 运行算法程序-进入区域
    data_output11 = check_region_entry(data_input, now_timestamp)
    # 打印算法结果
    print(f'check_region_entry: {data_output11}')

    # 运行算法程序-飞向飞离区域
    data_output12 = check_region_approach_departure(data_input, now_timestamp)
    # 打印算法结果
    print(f'check_region_approach_departure: {data_output12}')

    # # 可视化工作模式和盘旋模式航段
    # if data_output9 or data_output10:
    #     print("\n正在生成飞行模式航段的可视化图...")
    #     visualize_working_modes(data_input, data_output10, data_output9, output_dir='visualizations')
    #     print("可视化图生成完毕，请查看 'visualizations' 文件夹。")


